<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@include file="../hy/common.jsp"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" href="${pageContext.request.contextPath }/pages/zc/css/customer.css">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>客户管理</title>
<script type="text/javascript">
	$(function(){
		//1.初始化Table
		var oTable = new TableInit();
		oTable.Init();
		//2.初始化Button的点击事件
		var oButtonInit = new ButtonInit();
		oButtonInit.Init();
	});
	layui.use([ 'laydate' ], function() {
		var laydate = layui.laydate;
	});
	var TableInit = function () {
	    var oTableInit = new Object();
	    //初始化Table
	    oTableInit.Init=function(){
	    	$("#tb_departments").bootstrapTable({
	    		url: '${pageContext.request.contextPath }/customer/selectAllCustomer.do',//请求后台的url
	    		 method: 'get',                     	//请求方式（*）
		            toolbar: '#toolbar',                //工具按钮用哪个容器
		            striped: true,                      //是否显示行间隔色
		            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
		            pagination: true,                   //是否显示分页（*）
		            sortable: false,                     //是否启用排序
		            sortOrder: "asc",                   //排序方式
		            queryParams: oTableInit.queryParams,//传递参数（*）
		            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
		            pageNumber:1,                       //初始化加载第一页，默认第一页
		            pageSize: 10,                       //每页的记录行数（*）
		            pageList: [10, 20, 30],        		//可供选择的每页的行数（*）
		            clickToSelect: true,                //是否启用点击选中行
		            height: 550,                        //行高，如果没有设置height属性，表格自动根据记录条数觉得表格高度
		            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
		            detailView: false,                   //是否显示父子表
		            showExport: true,  //是否显示导出按钮  
	            columns:[{
	            	checkbox:true
	            },{
	            	field:'name',
	            	title:'客户名称'
	            },{
	            	field:'type',
	            	title:'客户类型'
	            },{
	            	field:'linkman',
	            	title:'联系人'
	            },{
	            	field:'phone',
	            	title:'联系电话'
	            },{
	            	field:'delivery',
	            	title:'运送方式'
	            },{
	            	field:'payments',
	            	title:'结算方式'
	            },{
	            	field:'paydate',
	            	title:'付款周期'
	            },{
	            	field:'enter',
	            	title:'录入人'
	            },{
	            	field:'enterDate',
	            	title:'录入日期'
	            }]
	    	});
	    }
	    //得到查询的参数
	    oTableInit.queryParams = function (params) {
	        var temp = {   //这里的键的名字和控制器的变量名必须一直，这边改动，控制器也需要改成一样的
	            limit: params.limit,   //页面大小
	            offset: params.offset,  //页码
	            name: $("#name1").val(),
	            type: $("#type1").val()
	            
	        };
	        return temp;
	    };
	    return oTableInit;
	}
	var ButtonInit = function () {
	    var oInit = new Object();
	    var postdata = {};

	    oInit.Init = function () {
	        //初始化页面上面的按钮事件
	    };

	    return oInit;
	};
	
	//添加
	function doAdd() {
		$("#addForm")[0].reset();//打开模态框前进行重置
		$("#addModal").modal(open);
		//添加数据+检验
		$(function() {
			var layerTips = parent.layer === undefined ? layui.layer : parent.layer
			$("#addModal").bootstrapValidator({
					feedbackIcons : {
						valid : 'glyphicon glyphicon-ok',
						invalid : 'glyphicon glyphicon-remove',
						validating : 'glyphicon glyphicon-refresh'
					},
					fields : {
						name : {
						validators : {
							notEmpty : {
								message : '客户名称不能为空'
							},
							callback: {
	                            message: '客户名称不能重复',
	                            callback:function(value, validator){
	                                var flg = false;
	                                $.ajax({
	                                    type:'post',
	                                    data:'name='+value,
	                                    url:'${pageContext.request.contextPath}/customer/selectCustomerByName.do',
						                dataType: 'JSON',
						                async: false,
	                                    success:function (data) {
	                                        if(data == 0){
	                                            flg  = true;
	                                        }else{
	                                            flg = false;
	                                        }

	                                    }
	                                });
	                                return flg;
	                            }
	                        },
						},
					},
					/* type : {
						validators : {
							notEmpty : {
								message : '客户类型不能为空'
							},
						},
					},
					linkman : {
						validators : {
							notEmpty : {
								message : '联系人不能为空'
							},
						},
					}, */
					phone : {
						validators : {
							/* notEmpty : {
								message : '联系电话不能为空'
							}, */
							stringLength: {
		                         min: 11,
		                         max: 11,
		                         message: '请输入联系电话号码'
		                     }, 
							regexp: {
	                         regexp:    /^(0?(13[0-9]|15[012356789]|17[013678]|18[0-9]|14[57])[0-9]{8})|(400|800)([0-9\\-]{7,10})|(([0-9]{4}|[0-9]{3})(-| )?)?([0-9]{7,8})((-| |转)*([0-9]{1,4}))?$/,
	                         message: '请输入正确的联系电话号码'
	                     }
						},
					},
					/*
					delivery : {
						validators : {
							notEmpty : {
								message : '运送方式不能为空'
							},
						},
					},
					payments : {
						validators : {
							notEmpty : {
								message : '结算方式不能为空'
							},
						},
					},
					paydate : {
						validators : {
							notEmpty : {
								message : '付款周期不能为空'
							},
						},
					}, */
				},
			}).on('success.form.bv',function() {
				$.ajax({
					type : 'post',
					url : '${pageContext.request.contextPath }/customer/createCustomer.do',
					data : $("#addForm").serialize(),
					async:false,
					success : function(data) {
						if (data==1) {
							toastr.success("新增成功");
							setTimeout(function(){
								window.location.reload();
							},2000);
						} else if (data==2) {
							toastr.warning("该信息已存在，不能重复添加");
							setTimeout(function(){
								window.location.reload();
							},2000);
						}else {
							toastr.warning("新增失败");
						}
					}
				});
			});
	});
}
	
	//删除
	function doDel() {
		var a= $('#tb_departments').bootstrapTable('getSelections');  
        var ids = "";
        for(var i = 0;i<a.length;i++) {
       	 if(i != a.length-1) {
       	 	ids +=a[i].id+",";
       	 }else {
       	 	ids +=a[i].id;
       	 }
        }
        //alert(ids)
		 if(a.length>0) {
			//询问框
			Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
				function(e) {
					if (!e) {return;}
					 $.ajax({
							type: "get",
							url: '${pageContext.request.contextPath }/customer/deleteCustomer.do',
							data: {ids:ids},
							success: function(data){
								if(data > 0) {
									toastr.success("删除成功！"); 
									setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
										//关闭模态框
										// 父页面刷新
										window.location.reload(); 
									},2000);
								}
								if(data==-1){
									toastr.warning('删除失败，客户已在别处关联！');
									setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
										//关闭模态框
										// 父页面刷新
										window.location.reload(); 
									},2000);
								}
							}
						});
				});
		}else {
			toastr.warning('请至少选择一条数据');
		}
	}
	
	//查询
	function selectByOther() {
		$('#tb_departments').bootstrapTable('refresh');
	}
	//导出当前页
	function doExport() {
		window.location.href="${pageContext.request.contextPath }/customer/export.do?exportType=1";
	}
	//导出所有
	/* function exportAll() {
		window.location.href="${pageContext.request.contextPath }/customer/export.do?exportType=2";
	} */
	function exportAll() {
		Ewin.confirm({message : "确认要导出所有数据吗？"}).on(
			function(e) {
				if (!e) {return;}
			window.location.href="${pageContext.request.contextPath}/customer/export.do?exportType=2"; 
		})
	}
	
	//去修改
	function doEdit() {
		var a= $('#tb_departments').bootstrapTable('getSelections');  
		 if(a.length==1) {
			 $("#edit").modal(open);
			 $.ajax({
					type: "get",
					url: '${pageContext.request.contextPath }/customer/toEditCustomer.do',
					data: {id:a[0].id},
					success: function(data){
						var json = eval('('+ data +')');
						$('#name2').val($.trim(json.name )); 
						$('#id2').val($.trim(json.id)); 
						$('#type2').val($.trim(json.type)); 
						$('#linkman2').val($.trim(json.linkman)); 
						$('#phone2').val($.trim(json.phone)); 
						$('#delivery2').val($.trim(json.delivery)); 
						$('#payments2').val($.trim(json.payments)); 
						$('#paydate2').val($.trim(json.paydate)); 
						$('#enter2').val($.trim(json.enter)); 
						$('#enterDate2').val($.trim(json.enterDate)); 

					}
				});
		}else {
			toastr.warning('请选择一条数据');
		}
	}
	
	//保存修改
	function saveEdit() {
		
		$(function() {
			var layerTips = parent.layer === undefined ? layui.layer : parent.layer
			$("#edit").bootstrapValidator({
					feedbackIcons : {
						valid : 'glyphicon glyphicon-ok',
						invalid : 'glyphicon glyphicon-remove',
						validating : 'glyphicon glyphicon-refresh'
					},
					fields : {
						name : {
						validators : {
							notEmpty : {
								message : '客户名称不能为空'
							},
						},
					},
					/* type : {
						validators : {
							notEmpty : {
								message : '客户类型不能为空'
							},
						},
					},
					linkman : {
						validators : {
							notEmpty : {
								message : '联系人不能为空'
							},
						},
					},
					phone : {
						validators : {
							notEmpty : {
								message : '联系电话不能为空'
							},
						},
					},
					delivery : {
						validators : {
							notEmpty : {
								message : '运送方式不能为空'
							},
						},
					},
					payments : {
						validators : {
							notEmpty : {
								message : '结算方式不能为空'
							},
						},
					},
					paydate : {
						validators : {
							notEmpty : {
								message : '付款周期不能为空'
							},
						},
					}, */
				},
			}).on('success.form.bv',function() {
		
		//获取name值并去空格
	   	 var id=$.trim($("#id2").val());
	   	 var name=$.trim($("#name2").val());
	   	 var type=$.trim($("#type2").val());
	   	 var linkman=$.trim($("#linkman2").val());
	   	 var phone=$.trim($("#phone2").val());
	   	 var delivery=$.trim($("#delivery2").val());
	   	 var payments=$.trim($("#payments2").val());
	   	 var paydate=$.trim($("#paydate2").val());
	   	$.ajax({ 
	   		type: "get",  
		        url: "${pageContext.request.contextPath }/customer/editCustomer.do",  
		        data: {name:name,id:id,type:type,linkman:linkman,phone:phone,delivery:delivery,payments:payments,paydate:paydate},  
		        success: function (data) {  
		        	if(data == 1){
						toastr.success("修改成功！"); 
						setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload(); 
						},1000);
		        	}else {
		        		toastr.warning("修改失败");
					}
				}
		    });
		   });
	    });
	}
	
	//关闭添加表单时清空数据
	function resets() {
		$('#addForm').data('bootstrapValidator').resetForm(true);
	}
	function douploadModal() {
		$('#uploadModal').modal(open);
		//清空表单
		document.getElementById("importForm").reset();
	}
	function uploadBtn() {
		 var fileName = $("#fileInput").val();
		 //alert(fileName);
		 if (fileName.length > 0) {
		     var formData = new FormData($("#importForm")[0]);  
		     $.ajax({ 
		          url: '${pageContext.request.contextPath}/customer/uplodeFile.do' ,  
		          data: formData,
		          type:'post',
		          async: false,  
		          cache: false,
		          contentType: false,  
		          processData: false,
		          success: function (data) {
		        	  if (data == 1) {
		        		  toastr.success('文件导入成功（重复数据已过虑）！');
		        		  setTimeout(function(){  //使用  setTimeout（）方法设定定时
								window.location.reload(); 
						  },3000);
		        	  }else{
		        		  toastr.warning('文件格式异常，文件导入失败！');  
		        	  }
		          },
		          error: function (data) {
		        	  toastr.error("文件格式异常，导入的数据不符合导入条件");  
		          }
		     }); 
		 }else{
			 toastr.warning('上传文件为空，请选择要导入的文件！');  
		}
	}
	//导出数据模板
	function doExportFile() {
		Ewin.confirm({message : "确认要导出数据模板吗？"}).on(
			function(e) {
				if (!e) {return;}
			window.location.href="${pageContext.request.contextPath}/customer/doExportFile.do"; 
			$('#uploadModal').modal('hide'); 
		})
	}
	
	toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上
</script>
</head>
<body>
<div class="modal fade" id="uploadModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
   		<div class="modal-dialog" role="document">
    		<div class="modal-content">
      			<div class="modal-header">
        			<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        			<h4 class="modal-title" id="exampleModalLabel">
        				<span style="font-size:13px">excel导入</span>
        			</h4>
      			</div>
      			<div class="modal-body">
	        		<form id="importForm" class="form-horizontal">
	        			<div class="form-group">
							<label  class="col-sm-3 control-label"></label>
							<div class="col-sm-7"> 
		           				 <button id="btn_delete" type="button" class="btn btn-default" onclick="doExportFile()">
					                <span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出数据模板
					            </button>
	          				 </div>
	          			</div>
	          			<div class="form-group">
				            <label class="col-sm-5 control-label">excel文件:</label>
				            <div class="col-sm-5"> 
					            <input id="fileInput" name="file" type="file" accept=".xls,.xlsx"/>
	          				</div>
	          			</div>
	        			<div class="form-group"> 
				   			<div class="col-sm-3 col-sm-offset-7">  
						        <button type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
						        <button type="submit"  name="submit"  class="btn btn-primary" id="ss" onclick="uploadBtn()">导入</button>
			      			</div>
			      		</div>
	        		</form>
	      		</div>
    		</div>
  		</div>
	</div>


<div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <form id="formSearch" class="form-horizontal">
                    <div class="form-group" style="margin-top:15px">
                        <label class="control-label col-sm-1" for="name1">客户名称</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="name1">
                        </div>
                        <label class="control-label col-sm-1" for="type1">客户类型</label>
                        <div class="col-sm-3">
                            <input type="text" class="form-control" id="type1">
                        </div>
                        <div class="col-sm-4" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary" onclick="selectByOther()">查询</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>       
		<div id="toolbar" class="btn-group">
			<button id="btn_add" type="button" class="btn btn-default" onclick="doAdd()">
				<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
			</button>
			<button id="btn_edit" type="button" class="btn btn-default" onclick="doEdit()">
				<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
			</button>
			<button id="btn_delete" onclick="doDel()" type="button" class="btn btn-default">
				<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
			</button>
			<!--<button id="btn_export" type="button" class="btn btn-default" onclick="doExport()">
				<span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出当前页
			</button>-->
			<button id="btn_import" type="button" class="btn btn-default" onclick="douploadModal()">
           		<span class="glyphicon glyphicon-bullhorn" aria-hidden="true"></span>导入
        	</button>
			<button id="btn_export" type="button" class="btn btn-default" onclick="exportAll()">
				<span class="glyphicon glyphicon-export" aria-hidden="true"></span>导出全部
			</button>
			<button id="btn_hide" type="button" class="btn btn-default" style="display: none;">
				<span class="glyphicon glyphicon-cancel" aria-hidden="true"></span>隐藏
			</button>
		</div>
		<table id="tb_departments"></table>
</div>
		<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
		<!-- data-backdrop="static" data-keyboard="false" -->
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true" onclick="resets()">&times;</button>
					<h4 class="modal-title" id="addModalLabel">新增客户信息</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="addForm" method="post">
						<div class="form-group">
							<label for="name" class="col-sm-3 control-label">客户名称:</label>
							<div class="col-sm-8" style="width: 385px;">
								<input type="text" id="name" name="name" class="form-control" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="type" class="col-sm-3 control-label">客户类型:</label>
							<div class="col-sm-9">
								<input type="text" id="type" name="type" class="form-control" style="width: 85%;" >
							</div>
						</div>
						<div class="form-group">
							<label for="linkman" class="col-sm-3 control-label">联系人:</label>
							<div class="col-sm-9">
								<input type="text" id="linkman" name="linkman" class="form-control" style="width: 85%;">
							</div>
						</div>
						<div class="form-group">
							<label for="phone" class="col-sm-3 control-label">联系电话:</label>
							<div class="col-sm-9">
								<input type="text" id="phone" name="phone" class="form-control" style="width: 85%;" lay-verify="phone">
							</div>
						</div>
						<div class="form-group">
							<label for="delivery" class="col-sm-3 control-label">运送方式:</label>
							<div class="col-sm-9">
								<input type="text" id="delivery" name="delivery" class="form-control" style="width: 85%;">
							</div>
						</div>
						<div class="form-group">
							<label for="payments" class="col-sm-3 control-label">结算方式:</label>
							<div class="col-sm-9">
								<input type="text" id="payments" name="payments" class="form-control" style="width: 85%;">
							</div>
						</div>
						<div class="form-group">
							<label for="paydate" class="col-sm-3 control-label">付款周期:</label>
							<div class="col-sm-9">
								<input type="text" id="paydate" name="paydate" class="form-control" style="width: 85%;">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal" onclick="resets()">关闭</button>
							<button type="submit" class="btn btn-primary">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	<!-- 修改 -->
	<div class="modal fade" id="edit" tabindex="-1" role="dialog"
		aria-labelledby="updateModalLabel" aria-hidden="true"
		data-backdrop="static" data-keyboard="false">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="updateModalLabel">修改客户信息</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form">
						<div class="form-group">
							<label for="name2" class="col-sm-3 control-label">客户名称:</label>
							<div class="col-sm-8" style="width: 385px;">
								<input type="text" id="name2" name="name2" class="form-control" data-bv-notempty="true" readonly="true">
								<span class="xing"></span>
							</div>
							 <input type="hidden" id="id2" name="id">
						</div>
						<div class="form-group">
							<label for="type2" class="col-sm-3 control-label">客户类型:</label>
							<div class="col-sm-9">
								<input type="text" id="type2" name="type2" class="form-control" style="width: 85%;" >
							</div>
						</div>
						<div class="form-group">
							<label for="linkman2" class="col-sm-3 control-label">联系人:</label>
							<div class="col-sm-9">
								<input type="text" id="linkman2" name="linkman2" class="form-control" style="width: 85%;" >
							</div>
						</div>
						<div class="form-group">
							<label for="phone2" class="col-sm-3 control-label">联系电话:</label>
							<div class="col-sm-9">
								<input type="text" id="phone2" name="phone2" class="form-control" style="width: 85%;" lay-verify="phone">
							</div>
						</div>
						<div class="form-group">
							<label for="delivery2" class="col-sm-3 control-label">运送方式:</label>
							<div class="col-sm-9">
								<input type="text" id="delivery2" name="delivery2" class="form-control" style="width: 85%;" >
							</div>
						</div>
						<div class="form-group">
							<label for="payments2" class="col-sm-3 control-label">结算方式:</label>
							<div class="col-sm-9">
								<input type="text" id="payments2" name="payments2" class="form-control" style="width: 85%;" >
							</div>
						</div>
						<div class="form-group">
							<label for="paydate2" class="col-sm-3 control-label">付款周期:</label>
							<div class="col-sm-9">
								<input type="text" id="paydate2" name="paydate2" class="form-control" style="width: 85%;" >
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal" onclick="resets()">关闭</button>
							<button type="submit" class="btn btn-primary" onclick="saveEdit()">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
</body>
</html>